package com.earthea.common.util;

import cn.hutool.crypto.digest.DigestAlgorithm;
import com.google.common.base.Preconditions;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 编码工具
 */
public class CodecUtils {

    public static String digest(DigestAlgorithm algorithm, String text, String salt) {
        Preconditions.checkNotNull(algorithm, "algorithm cannot be null");
        Preconditions.checkNotNull(text, "text cannot be null");
        return Hex.encodeHexString(digest(algorithm, text.getBytes(StandardCharsets.UTF_8), salt));
    }

    public static String digest(DigestAlgorithm algorithm, InputStream is, String salt) throws IOException {
        Preconditions.checkNotNull(algorithm, "algorithm cannot be null");
        Preconditions.checkNotNull(is, "is cannot be null");
        return Hex.encodeHexString(digest(algorithm, IOUtils.toByteArray(is), salt));
    }

    public static String digest(DigestAlgorithm algorithm, Object obj, String salt) {
        Preconditions.checkNotNull(algorithm, "algorithm cannot be null");
        Preconditions.checkNotNull(obj, "obj cannot be null");
        return Hex.encodeHexString(digest(algorithm, obj.toString().getBytes(StandardCharsets.UTF_8), salt));
    }

    private static byte[] digest(DigestAlgorithm algorithm, byte[] data, String salt) {
        MessageDigest messageDigest = DigestUtils.getDigest(algorithm.getValue());
        messageDigest.update(data);
        if (StringUtils.isNotBlank(salt)) {
            messageDigest.update(salt.getBytes(StandardCharsets.UTF_8));
        }
        return messageDigest.digest();
    }
}
